import AgoraRTC from 'agora-rtc-sdk-ng'

// 简单的事件发射器实现
class SimpleEventEmitter {
  constructor() {
    this.events = {}
  }
  
  on(event, listener) {
    if (!this.events[event]) {
      this.events[event] = []
    }
    this.events[event].push(listener)
  }
  
  emit(event, ...args) {
    if (this.events[event]) {
      this.events[event].forEach(listener => listener(...args))
    }
  }
  
  off(event, listener) {
    if (this.events[event]) {
      this.events[event] = this.events[event].filter(l => l !== listener)
    }
  }
}

class RTCManager extends SimpleEventEmitter {
  constructor() {
    super()
    this.client = null
    this.localAudioTrack = null
    this.localVideoTrack = null
    this.remoteUsers = {}
  }

  async init(options) {
    this.options = options
    this.client = AgoraRTC.createClient({ mode: 'rtc', codec: 'vp8' })
    
    this.client.on('user-published', async (user, mediaType) => {
      await this.client.subscribe(user, mediaType)
      
      // ⚠️ 不自动播放音频，由上层（aiChat.vue）根据模式决定是否播放
      // 视频模式：音频在视频中，不需要播放 RTC 音频
      // 音频模式：aiChat.vue 会手动调用 play()
      // if (mediaType === 'audio') {
      //   user.audioTrack?.play()
      // }
      
      if (mediaType === 'video') {
        this.remoteUsers[user.uid] = user
        this.emit('remoteUserChanged', Object.values(this.remoteUsers))
      }
    })
    
    this.client.on('user-unpublished', (user) => {
      if (this.remoteUsers[user.uid]) {
        delete this.remoteUsers[user.uid]
        this.emit('remoteUserChanged', Object.values(this.remoteUsers))
      }
    })
  }
  
  async createMicrophoneAudioTrack() {
    this.localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack()
    this.emit('localTracksChanged', {
      audioTrack: this.localAudioTrack,
      videoTrack: this.localVideoTrack
    })
  }
  
  async createCameraVideoTrack() {
    this.localVideoTrack = await AgoraRTC.createCameraVideoTrack()
    this.emit('localTracksChanged', {
      audioTrack: this.localAudioTrack,
      videoTrack: this.localVideoTrack
    })
  }
  
  async join() {
    await this.client.join(
      this.options.appId,
      this.options.channel,
      this.options.token,
      this.options.uid
    )
    
    if (this.localAudioTrack) {
      await this.client.publish(this.localAudioTrack)
    }
    
    if (this.localVideoTrack) {
      await this.client.publish(this.localVideoTrack)
    }
  }
  
  async muteLocalAudioTrack() {
    await this.localAudioTrack?.setMuted(true)
  }
  
  async unmuteLocalAudioTrack() {
    await this.localAudioTrack?.setMuted(false)
  }
  
  async muteLocalVideoTrack() {
    await this.localVideoTrack?.setMuted(true)
  }
  
  async unmuteLocalVideoTrack() {
    await this.localVideoTrack?.setMuted(false)
  }
  
  async leave() {
    console.log('RTCManager leaving...')
    
    // 停止所有远程用户的音频播放
    Object.values(this.remoteUsers).forEach(user => {
      if (user.audioTrack) {
        user.audioTrack.stop()
        console.log('Stopped remote audio track for user:', user.uid)
      }
      if (user.videoTrack) {
        user.videoTrack.stop()
        console.log('Stopped remote video track for user:', user.uid)
      }
    })
    
    // 关闭本地轨道
    if (this.localAudioTrack) {
      this.localAudioTrack.close()
      this.localAudioTrack = null
      console.log('Local audio track closed')
    }
    
    if (this.localVideoTrack) {
      this.localVideoTrack.close()
      this.localVideoTrack = null
      console.log('Local video track closed')
    }
    
    // 清空远程用户
    this.remoteUsers = {}
    
    // 离开频道
    if (this.client) {
      await this.client.leave()
      console.log('RTC client left channel')
    }
  }
}

export const rtcManager = new RTCManager()
